import 'dart:async';
import 'dart:io';
import 'dart:ui';
import 'package:e_reception_flutter/media_library/media_library_index/widgets/logo_widget.dart';
import 'package:e_reception_flutter/media_library/media_library_index/widgets/watermark_text_widget.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'custom_video_cache_manager.dart';

class WatermarkTextVideoDelegate extends DefaultPhotoPreviewVideoDelegate{

  StreamController<bool> _isSlideStream = StreamController.broadcast();
  StreamController<double> _picHeightStream;
  Stream<FileResponse> _fileStream;
  CustomVideoCacheManager _customVideoCacheManager;

  @override
  ValueChanged<bool> get isSlidingStatus {
    return (status){
      _isSlideStream?.add(status);
    };
  }

  @override
  SlideEndHandler get slideEndHandler =>  (
      Offset offset, {
        ExtendedImageSlidePageState state,
        ScaleEndDetails details,
      }) {
    //如果放大
    if ((state?.imageGestureState?.gestureDetails?.totalScale ??
        PhotoPreviewConstant.DEFAULT_TOTAL_SCALE) >
        (state?.imageGestureState?.imageGestureConfig?.initialScale ??
            PhotoPreviewConstant.DEFAULT_INIT_SCALE)) {
      return false;
    }
    //向上滑回弹
    if (offset.dy <= 0) {
      return false;
    }
    return offset.dy > 20;
  };

  @override
  void initState() {
    super.initState();
    //初始化缓存
    _customVideoCacheManager = CustomVideoCacheManager();
  }


  @override
  Widget videoWidget(PhotoPreviewInfoVo videoInfo,{Widget result,VideoPlayerController videoPlayerController,dynamic customVideoPlayerController}) {
    _picHeightStream = StreamController.broadcast();
    // double _bottomBarH = ScreenUtils.getBottomBarH(context);
    // double _bottom = 48 - ((_bottomBarH == 0)?15.0:0);
    if (PhotoPreviewToolUtils.isNetUrl(videoInfo.url)) {
      _fileStream = _customVideoCacheManager.getFileStream(videoInfo.url);
      _fileStream.listen((event) {
        FileInfo fileInfo = event as FileInfo;
        print("fileInfo:" + fileInfo.originalUrl);
        if (fileInfo.file != null){
          print("fileInfo:" + fileInfo.file.path);
          videoInfo = PhotoPreviewInfoVo(
              url: fileInfo.file.path,
              loadingCoverUrl: videoInfo?.loadingCoverUrl,
              type: videoInfo?.type,
              heroTag: videoInfo?.heroTag,
              extra: videoInfo?.extra
          );
          videoPlayerController =
              VideoPlayerController.file(File(fileInfo.file.path));
        }
        print("fileInfo:" + fileInfo.source.toString());
        print("fileInfo:" + fileInfo.validTill.toIso8601String());
      });

    }
    return Stack(
      fit: StackFit.expand,
      children: <Widget>[
        result,
        StreamBuilder<double>(
          stream: _picHeightStream?.stream,
          builder: (context, snapshot){
            if(snapshot?.data == null){
              return Container();
            }
            return Container(
              margin: (snapshot.data <=0)?EdgeInsets.only(bottom: 48):EdgeInsets.only(bottom: snapshot?.data??1),
              child: Align(
                alignment: Alignment.bottomCenter,
                child: StreamBuilder<bool>(
                    initialData: false,
                    stream: _isSlideStream?.stream,
                    builder: (context, snapshot) {
                      return AnimatedOpacity(
                        opacity: snapshot?.data == true ? 0: 1,
                        duration: Duration(milliseconds: 50),
                        child: (videoInfo?.extra != null)? WatermarkTextWidget(
                            id: videoInfo?.extra['id'] ?? "",
                            watermark: videoInfo?.extra['watermark'] ?? "",
                            waterflg: videoInfo?.extra['waterflg'] ?? "",
                            title: videoInfo?.extra['title'] ?? "",
                            content: videoInfo?.extra['content'] ?? ""
                        ):SizedBox(),
                      );
                    }
                ),
              ),
            );
          },
        ),
        (videoInfo?.extra != null && ("00" == (videoInfo?.extra['logoflg']??"")) && StringUtils.isNotEmpty(videoInfo?.extra['logo']??""))?
        StreamBuilder<double>(
            stream: _picHeightStream?.stream,
            builder: (context, snapshot) {
              if(snapshot?.data == null){
                return Container();
              }
              return Container(
                margin: (snapshot.data <=0)?EdgeInsets.only(top: ScreenUtils.getStatusBarH(context)):EdgeInsets.only(top: snapshot?.data??1),
                child: Align(
                  alignment: Alignment.topRight,
                  child: StreamBuilder<bool>(
                      initialData: false,
                      stream: _isSlideStream?.stream,
                      builder: (context, snapshot) {
                        return AnimatedOpacity(
                          opacity: snapshot?.data == true ? 0: 1,
                          duration: Duration(milliseconds: 50),
                          child: (videoInfo?.extra != null)? LogoWidget(
                            logo: videoInfo?.extra['logo'] ?? "",
                          ):SizedBox(),
                        );
                      }
                  ),
                ),
              );
            }
        )
            :SizedBox(),
      ],
    );
  }

  @override
  void dispose() {
    _isSlideStream?.close();
    super.dispose();
  }

  @override
  Function(double width, double height) get afterPaintImage {
    return (width, height){
      if(width >= height){
        _picHeightStream?.add(0);
      }else{
        _picHeightStream?.add(((ScreenUtils.screenH(context) - height)/2 - 2));
      }
    };
  }

  static Future<String> transUrl(String localUrl)async{
    if (PhotoPreviewToolUtils.isNetUrl(localUrl) && (PhotoPreviewType.video == PhotoPreviewToolUtils.getType(localUrl))) {
      FileInfo cacheFile = await CustomVideoCacheManager().getFileFromCache(localUrl);
      if(cacheFile != null && cacheFile.file != null){
        return cacheFile.file.path;
      }
    }
    return localUrl;
  }

}
